package com.quiz.action.sdk.utils;

import android.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Arrays;

public class QActionUtils {
    private static final String SECRET_KEY = "Rf4AVBMrWuMcq2mk";

    // GCM参数
    private static final int GCM_TAG_LENGTH = 128;
    private static final int GCM_IV_LENGTH = 12;

    // 算法/模式/参数
    private static final String TRANSFORMATION = "AES/GCM/NoPadding";

//    public static String encrypt(String plainText) {
//        try {
//            SecretKey secretKey = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), "AES");
//            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
//
//            // 生成随机IV
//            byte[] iv = new byte[GCM_IV_LENGTH];
//            SecureRandom secureRandom = new SecureRandom();
//            secureRandom.nextBytes(iv);
//
//            // 初始化Cipher
//            GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH, iv);
//            cipher.init(Cipher.ENCRYPT_MODE, secretKey, gcmParameterSpec);
//
//            // 加密并拼接IV和密文
//            byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
//            byte[] ivAndEncrypted = new byte[iv.length + encryptedBytes.length];
//            System.arraycopy(iv, 0, ivAndEncrypted, 0, iv.length);
//            System.arraycopy(encryptedBytes, 0, ivAndEncrypted, iv.length, encryptedBytes.length);
//
//            return Base64.encodeToString(ivAndEncrypted, Base64.DEFAULT);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//    }


    public static String decrypt(String encryptedText) {
        try {
            SecretKey secretKey = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), "AES");
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);

            byte[] ivAndEncrypted = Base64.decode(encryptedText, Base64.DEFAULT);
            byte[] iv = Arrays.copyOfRange(ivAndEncrypted, 0, GCM_IV_LENGTH);
            byte[] ciphertext = Arrays.copyOfRange(ivAndEncrypted, GCM_IV_LENGTH, ivAndEncrypted.length);

            GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH, iv);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec);

            byte[] decryptedBytes = cipher.doFinal(ciphertext);
            return new String(decryptedBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
